package com.csj.mvvm.api.retrofit

import android.annotation.SuppressLint
import com.csj.mvvm.App
import com.csj.mvvm.api.ApiService
import com.csj.mvvm.api.URLConstant
import com.csj.mvvm.api.interceptor.LoggingInterceptor
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.*

class RetrofitClient {

    companion object {
        private var instance: RetrofitClient? = null
        fun getInstance() = instance ?: RetrofitClient().also { instance = it }

        private lateinit var retrofit: Retrofit
    }

    private var cookieJar: PersistentCookieJar = PersistentCookieJar(
        SetCookieCache(),
        SharedPrefsCookiePersistor(App.instance)
    )

    init {
        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(URLConstant.BASE_URL)
            .build()
    }

    private fun getOkHttpClient(): OkHttpClient {
        //IgnoreVerifySSL
        val trustManager = @SuppressLint("CustomX509TrustManager")
        object : X509TrustManager {
            @SuppressLint("TrustAllX509TrustManager")
            @Throws(CertificateException::class)
            override fun checkClientTrusted(
                chain: Array<java.security.cert.X509Certificate>, authType: String
            ) {
            }

            @SuppressLint("TrustAllX509TrustManager")
            @Throws(CertificateException::class)
            override fun checkServerTrusted(
                chain: Array<java.security.cert.X509Certificate>,
                authType: String
            ) {
            }

            override fun getAcceptedIssuers(): Array<X509Certificate?> {
                return arrayOfNulls(0)
            }
        }
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, arrayOf<X509TrustManager>(trustManager), SecureRandom())
        return OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .cookieJar(cookieJar)
            .addInterceptor(LoggingInterceptor())
//            .sslSocketFactory(SSLContextSecurity.createIgnoreVerifySSL("TLS"))
            .sslSocketFactory(sslContext.socketFactory,trustManager)
            .hostnameVerifier { _, _ -> true }
            .build()
    }

    fun create(): ApiService = retrofit.create(
        ApiService::class.java
    )

}